package com.lagou.edu.handler;

import com.alibaba.fastjson.JSON;
import com.lagou.edu.pojo.ServiceNodeInfo;
import com.lagou.edu.request.RpcRequest;
import com.lagou.edu.response.RpcResponse;
import com.lagou.edu.zookeeper.ZookeeperFactory;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.Date;
import java.util.concurrent.Callable;


/**
 * @author 赵虎
 * @date 2020/11/25 12:09
 */
public class ClientHandler extends ChannelInboundHandlerAdapter implements Callable {

    private ChannelHandlerContext context;
    private Object result;
    private RpcRequest rpcRequest;
    private String servicePath;
    private ZookeeperFactory zookeeperFactory;

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        context = ctx;
    }

    @Override
    public synchronized void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        RpcResponse rpcResponse = (RpcResponse) msg;
        System.out.println("请求结果------------->:" + rpcResponse);
        result = JSON.parseObject(JSON.toJSONString(rpcResponse.getData()), rpcRequest.getResultTypes());
        notify();
    }

    @Override
    public synchronized Object call() throws Exception {
        long startTime = System.currentTimeMillis();
        context.writeAndFlush(rpcRequest);
        wait();
        Date respTime = new Date();
        ServiceNodeInfo serviceNodeInfo = zookeeperFactory.getServiceValue(servicePath, ServiceNodeInfo.class);
        serviceNodeInfo.setUseTime(respTime.getTime() - startTime);
        serviceNodeInfo.setRespDate(respTime);
        zookeeperFactory.updateServiceValue(servicePath, serviceNodeInfo);
        return result;
    }

    public void close() {
        context.channel().close();
    }

    public void setRpcRequest(RpcRequest rpcRequest) {
        this.rpcRequest = rpcRequest;
    }

    public void setServicePath(String servicePath) {
        this.servicePath = servicePath;
    }

    public String getServicePath() {
        return servicePath;
    }

    public void setZookeeperFactory(ZookeeperFactory zookeeperFactory) {
        this.zookeeperFactory = zookeeperFactory;
    }
}
